package com.oms.wtj;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import net.sf.json.JSONObject;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 执行sql语句的工具类
 * 
 * @author 杨阳
 */
public class ExecuteSql {

	public static final ApplicationContext ctx = new ClassPathXmlApplicationContext("com/oms/wtj/appCtx-core.xml");
	public static final DefaultTransactionDefinition defaultTransaction = new DefaultTransactionDefinition();
	public static final DataSource dataSource = (DataSource) ctx.getBean("dataSource");
	public static final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	public static final PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);

	TransactionStatus status;

	public void getTransaction() {
		defaultTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		status = transactionManager.getTransaction(defaultTransaction);
	}

	public void rollBack() {
		transactionManager.rollback(status);
	}


	public Map<String, Object> queryForObject(String sql) {
		List<Map<String, Object>> l = this.queryForList(sql);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public int update(String sql, Object[] o) {
		int i = jdbcTemplate.update(sql, o);
		return i;
	}

	public int update(String sql) {
		return jdbcTemplate.update(sql);
	}

	public List<Map<String, Object>> queryForList(String sql) {
		System.out.println("2012年9月10日22:50:07："+sql);
		return jdbcTemplate.queryForList(sql);
	}

	public void execute(String sql) {
		jdbcTemplate.execute(sql);
	}
}
